import { resolve } from 'path';
import { loadEnv } from 'vite';
import type { UserConfig, ConfigEnv } from 'vite';
import Vue from '@vitejs/plugin-vue';
import VueJsx from '@vitejs/plugin-vue-jsx';
import { ViteEjsPlugin } from 'vite-plugin-ejs'; // 传统js模板兼容
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
// import { createStyleImportPlugin, ElementPlusResolve } from 'vite-plugin-style-import';
import { visualizer } from 'rollup-plugin-visualizer';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver, VantResolver } from 'unplugin-vue-components/resolvers';
import CompressPlugin from 'vite-plugin-compression';
import VueSetupExtend from 'vite-plugin-vue-setup-extend';
// import legacy from '@vitejs/plugin-legacy';
import SvgLoader from 'vite-svg-loader';
// @ts-ignore
import { CreateHtmlPlugin } from 'vite-plugin-html';
// import AutoImport from 'unplugin-auto-import/vite';

// 项目目录
const appRootPath = process.cwd();

function pathResolve(dir: string) {
  return resolve(appRootPath, '.', dir);
}

function rootPathResolve(dir: string) {
  return resolve(__dirname, dir);
}

export default ({ mode }: ConfigEnv): UserConfig => {
  // const isBuild = command === 'build';

  console.log('当前环境：', mode);

  const appEnv = loadEnv(mode, appRootPath);
  const rootEnv = loadEnv(mode, rootPathResolve('./env'));

  const env = {
    ...rootEnv,
    ...appEnv,
  };

  function loadEnvConfig() {
    if (!appEnv) {
      console.warn(`File ${appEnv} not found. Skipping...`);
      return {};
    }
    return Object.entries(env).reduce((acc, [key, value]) => {
      // @ts-ignore
      acc[`import.meta.env.${key}`] = JSON.stringify(value);
      return acc;
    }, {});
  }

  const importEnv = loadEnvConfig();

  return {
    base: env.VITE_PUBLIC_PATH,
    envDir: pathResolve('./'),
    define: {
      ...importEnv,
    },
    plugins: [
      Vue({
        script: {
          defineModel: true,
        },
      }),
      VueJsx(),
      createSvgIconsPlugin({
        iconDirs: [pathResolve('src/assets/svgs')],
        symbolId: 'icon-[dir]-[name]',
        svgoOptions: true,
      }),

      Components({
        resolvers: [
          ElementPlusResolver(),
          VantResolver(),
        ],
      }),
      // 生产环境 gzip 压缩资源
      CompressPlugin({ // 1
        ext: '.gz',
        deleteOriginFile: false,
      }),
      // 允许 setup 语法糖上添加组件名属性
      VueSetupExtend(),
      // legacy({
      //   targets: ['defaults', 'not IE 11', 'chrome 52'],
      // }),
      ViteEjsPlugin({
        ...env,
      }),
      // AutoImport({
      //   imports: ['vue', 'vue-router', 'pinia'], // 自动导入 vue 和 router
      //   // 声明文件生成位置和文件名称
      //   dts: './auto-imports.d.ts',
      // }),
      SvgLoader(),
      CreateHtmlPlugin({
        inject: {
          data: {
            ...env,
          },
        },
      }),
    ],

    css: {
      // preprocessorOptions: {
      //   less: {
      //     additionalData: '@import "./src/styles/variables.module.less";',
      //     javascriptEnabled: true,
      //   },
      // },
    },
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.less', '.css'],
      alias: [
        {
          find: /@\//,
          replacement: `${pathResolve('src')}/`,
        },
      ],
    },
    esbuild: {
      pure: env.VITE_DROP_CONSOLE === 'true' ? ['console.log'] : undefined,
      drop: env.VITE_DROP_DEBUGGER === 'true' ? ['debugger'] : undefined,
    },
    build: {
      target: 'es2015',
      outDir: env.VITE_OUTPUT_DIR || '/',
      sourcemap: env.VITE_SOURCEMAP === 'true',
      // brotliSize: false,
      rollupOptions: {
        plugins: env.VITE_USE_BUNDLE_ANALYZER === 'true' ? [visualizer()] : undefined,
        // 拆包
        output: {
          // manualChunks: {
          //   'vue-chunks': ['vue', 'vue-router', 'pinia', 'vue-i18n'],
          //   'element-plus': ['element-plus'],
          //   'wang-editor': ['@wangeditor/editor', '@wangeditor/editor-for-vue'],
          //   echarts: ['echarts', 'echarts-wordcloud'],
          // },
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        },
      },
      cssCodeSplit: !(env.VITE_USE_CSS_SPLIT === 'false'),
    },
    server: {
      port: 3000,
      hmr: {
        overlay: false,
      },
      host: '0.0.0.0',
    },
  };
};
